package com.solcoo.common.image;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.solcoo.common.App;
import com.solcoo.common.image.activity.CropActivity;

public class BitmapHelper {
	public final static int MAX_PHOTO_SIZE_320 = 320;
	public final static int MAX_PHOTO_SIZE_640 = 640;
	public static final int REQUEST_CODE_ALBUMN = 1;// 相册获取图片
	public static final int REQUEST_CODE_CAMERA = 2;// 拍照获取图片
	public static final int REQUEST_CODE_CUT = 0; // 裁剪图片
	public final static String JPG = ".jpg";
	private final static String TAG = "BitmapHelper";

	/**
	 * 检查是否有摄像头
	 */
	public static boolean checkCameraHardware() {
		if (!App.CONTEXT.getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA)) {
			new AlertDialog.Builder(App.CONTEXT)
					.setMessage("您的手机未检测到摄像头，暂时无法使用该功能！")
					.setPositiveButton("确定", null).show();
			return false;
		}
		return true;
	}

	/**
	 * 检测手机是否存在SD卡,网络连接是否打开
	 */
	public static boolean checkExternalStorageState() {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) { // 判断是否存在SD卡
			new AlertDialog.Builder(App.CONTEXT)
					.setMessage("检测到手机没有存储卡！请插入手机存储卡再开启本应用。")
					.setPositiveButton("确定", null).show();
			return false;
		}
		return true;
	}

	/**
	 * 读取照片
	 * 
	 * @param file
	 * @param outWidth
	 * @param outHeight
	 * @return
	 */
	public static Bitmap readBitmapAutoSize(File file, int outWidth,
			int outHeight) {
		// outWidth和outHeight是目标图片的最大宽度和高度，用作限制
		FileInputStream fs = null;
		BufferedInputStream bs = null;
		FileInputStream fsTemp = null;
		try {
			fs = new FileInputStream(file);
			bs = new BufferedInputStream(fs);
			Options options = setBitmapOption(bs, outWidth, outHeight);
			fsTemp = new FileInputStream(file);
			return BitmapFactory.decodeStream(fsTemp, null, options);
		} catch (Throwable e) {
			Log.e(TAG, "readBitmapAutoSize failed:", e);
		} finally {
			try {
				if (bs != null)
					bs.close();
				if (fs != null)
					fs.close();
				if (fsTemp != null)
					fsTemp.close();
			} catch (Exception e) {
				Log.e("readBitmapAutoSize close bs,fs failed", e.getMessage());
			}
		}
		return null;
	}

	/**
	 * 记录图片的基本信息 为压缩做准备
	 * 
	 * @param is
	 * @param width
	 * @param height
	 * @return
	 */
	private static Options setBitmapOption(InputStream is, int width, int height) {
		Options opt = new Options();
		opt.inJustDecodeBounds = true;
		// 设置只是解码图片的边距，此操作目的是度量图片的实际宽度和高度
		BitmapFactory.decodeStream(is, null, opt);
		int outWidth = opt.outWidth; // 获得图片的实际高和宽
		int outHeight = opt.outHeight;
		opt.inDither = false;
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		// 设置加载图片的颜色数为16bit，默认是RGB_8888，表示24bit颜色和透明通道，但一般用不上
		opt.inSampleSize = 1;
		// 设置缩放比,1表示原比例，2表示原来的四分之一....
		// 计算缩放比
		if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {
			int w = outWidth / width;
			int h = outHeight / height;
			int sampleSize = h > w ? h : w;
			opt.inSampleSize = sampleSize;
		}
		opt.inJustDecodeBounds = false;// 最后把标志复原
		// 设置图片的DPI为当前手机的屏幕dpi
		opt.inTargetDensity = App.getResources().getDisplayMetrics().densityDpi;
		opt.inScaled = true;
		return opt;
	}

	/**
	 * 
	 * @param bitmap
	 * @param file
	 * @return
	 */
	public static boolean storeImage(Bitmap bitmap, File file) {
		return storeImage(bitmap, file, 100);
	}

	/**
	 * 
	 * @param bitmap
	 * @param file
	 *            存储的文件
	 * @param quality
	 *            压缩品质
	 * @return
	 */
	public static boolean storeImage(Bitmap bitmap, File file, int quality) {
		OutputStream stream = null;
		try {
			stream = new FileOutputStream(file);
			return bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);// 转化
		} catch (FileNotFoundException e) {
			Log.e("storeImage failed", e.getMessage());
		} finally {
			try {
				if (stream != null)
					stream.close();
			} catch (IOException e) {
				Log.e("storeImage close stream failed", e.getMessage());
			}
		}
		return false;
	}

	/**
	 * 通过uri 获取图片文件
	 * 
	 * @param uri
	 * @return
	 */
	public static File getFileByUri(Uri uri) {

		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor actualimagecursor = App.CONTEXT.getContentResolver().query(uri,
				proj, null, null, null);
		int actual_image_column_index = actualimagecursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		actualimagecursor.moveToFirst();
		String img_path = actualimagecursor
				.getString(actual_image_column_index);
		Log.i("path", img_path);
		return new File(img_path);
	}

	public static void startPhotoCrop(String src, String desc,
			Activity activity, float scale, int x, int y) {
		Intent intent = new Intent(activity, CropActivity.class);
		intent.putExtra(CropActivity.CROP_IMAGE_URL, src);
		intent.putExtra(CropActivity.FRAME_SIZE_SCALE, scale);
		intent.putExtra(CropActivity.OUTPUT_X, x);
		intent.putExtra(CropActivity.OUTPUT_Y, y);
		intent.putExtra(CropActivity.OUTPUT_URL, desc);
		activity.startActivityForResult(intent, REQUEST_CODE_CUT);
	}
}
